import {
  selectSet,
  resetCurrentShape,
  currentShape,
  multipleSelectMode,
  mouseDirection,
} from '../data/shapes';
import { allowPaste, currentStage, stageConfig } from '../data/stage';
import { pasteShape, copyShape } from './shape.actions';
import { createBarcode, createImage, createQrcode, createRect, createText } from './shape.create';
import { unredo } from './undo.redo';

const altMap: any = {
  2() {
    createBarcode();
  },
  3() {
    createImage();
  },
  4() {
    createQrcode();
  },
  q() {
    createRect();
  },
  w() {
    createText();
  },
};

/* 带ctrl的快捷键 */
const ctrlMap: any = {
  /* 撤销 */
  z() {
    unredo.redo();
  },
  /* 反撤销 */
  y() {
    unredo.undo();
  },
  v() {
    if (allowPaste.value) {
      pasteShape();
    }
  },
  c() {
    copyShape();
  },
};
/* 全局响应的快捷键 */
const keyMap: any = {
  Delete() {
    Array.from(selectSet.value).forEach(id => {
      currentStage.value.components = currentStage.value.components.filter(item => {
        return item.id !== id;
      });
    });
    selectSet.value.clear();
    resetCurrentShape();
    unredo.save();
  },
  /* 向上移动 */
  ArrowUp() {
    if (currentShape.value.y <= 0) return;
    currentShape.value.y -= 1;
  },
  ArrowRight() {
    if (currentShape.value.x + currentShape.value.w >= stageConfig.value.w) return;
    currentShape.value.x += 1;
  },
  ArrowLeft() {
    if (currentShape.value.x <= 0) return;
    currentShape.value.x -= 1;
  },
  ArrowDown() {
    if (currentShape.value.y + currentShape.value.h >= stageConfig.value.h) return;
    currentShape.value.y += 1;
  },
  /* 取消 */
  Escape() {
    selectSet.value.clear();
  },
};
/**
 * 注释:全局快捷键
 *
 * */

const keydown = (e: KeyboardEvent) => {
  if (e.ctrlKey) {
    /* 多选模式 */
    if (!multipleSelectMode.value) {
      multipleSelectMode.value = !multipleSelectMode.value;
    }

    // eslint-disable-next-line no-unused-expressions
    !!ctrlMap[e.key] && ctrlMap[e.key]();
  }
  if (e.altKey) {
    // eslint-disable-next-line no-unused-expressions
    !!altMap[e.key] && altMap[e.key]();
  }
  /* 直接响应的按键 */
  if (keyMap[e.key]) {
    if (allowPaste.value) keyMap[e.key]();
  }
  if (e.shiftKey && mouseDirection.value) {
    currentShape.value.axis = 'y';
  } else if (e.shiftKey) {
    currentShape.value.axis = 'x';
  }
  if (e.shiftKey) {
    currentShape.value.lockAspectRatio = true;
  }
};
/**
 * 注释: 键盘弹起释放事件
 *
 * */
const keyup = (e: KeyboardEvent) => {
  currentShape.value.lockAspectRatio = false;
  /* ctrlKey键多选 */
  if (!e.ctrlKey && multipleSelectMode.value) {
    /* 多选模式 */
    multipleSelectMode.value = false;
  }
  currentShape.value.axis = 'both';
  if (currentShape.value.type === 'qrcode' || currentShape.value.type === 'd-qrcode') {
    currentShape.value.lockAspectRatio = true;
  }
};
/* 键盘按下的快捷键 */
window.addEventListener('keydown', keydown);
window.addEventListener('keyup', keyup);
window.addEventListener('blur', () => {
  currentShape.value.axis = 'both';
});
